/*
 * Copyright (c) 2020 IUV Inc. All rights reserved.
 * 项目名称：IUV TXY
 * 文件名：ImFriendServiceImpl.java
 * Date：20-10-23 下午4:54
 * Author：Will
 */

package com.iuv.imdemo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iuv.config.ImSetting;
import com.iuv.imdemo.dto.FriendInfo;
import com.iuv.imdemo.dto.FrindPageBean;
import com.iuv.imdemo.service.ImAccountService;
import com.iuv.imdemo.service.ImFriendService;
import com.iuv.imdemo.util.ImRequsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * IM例子-IM服务好友关系业务实现类
 *
 * @author Will
 * @date 16:54
 */
@Service("imFriendService")
public class ImFriendServiceImpl implements ImFriendService {
    private final static Logger logger = LoggerFactory.getLogger(ImFriendServiceImpl.class);
    @Autowired
    private ImAccountService imAccountService;

    /**
     * 添加好友
     *
     * @param userId
     * @param friendUserId
     * @param remark
     * @return
     */
    @Override
    public boolean addFirend(String userId, String friendUserId, String remark) {
        boolean isAddSuccess = false;
        JSONObject postData = new JSONObject();
        postData.put("From_Account", userId);
        JSONObject friendItem = new JSONObject();
        friendItem.put("To_Account", friendUserId);
        friendItem.put("Remark", remark);
        friendItem.put("AddSource", "AddSource_Type_Web");
        JSONArray addFriendItem = new JSONArray();
        addFriendItem.add(friendItem);
        postData.put("AddFriendItem", addFriendItem);
        postData.put("AddType", "Add_Type_Both");
        postData.put("ForceAddFlags", 0);
        String userSig = imAccountService.genUserSig(ImSetting.IDENTIFIER);
        JSONObject respond = ImRequsetUtil.request("v4/sns/friend_add", userSig, postData.toJSONString());
        logger.info(respond.toJSONString());
        if (respond != null) {
            String actionStatus = (String) respond.get("ActionStatus");
            if ("OK".equalsIgnoreCase(actionStatus)) {
                JSONArray resultItem = respond.getJSONArray("ResultItem");
                if (resultItem != null && resultItem.size() > 0) {
                    for (int i = 0; i < resultItem.size(); i++) {
                        JSONObject result = resultItem.getJSONObject(i);
                        if ("0".equalsIgnoreCase(result.getString("ResultCode"))) {
                            isAddSuccess = true;
                        }
                    }
                }
            }
        }

        return isAddSuccess;
    }

    private boolean imRequest(JSONObject postData, String requestUrl) {
        String userSig = imAccountService.genUserSig(ImSetting.IDENTIFIER);
        logger.info("request:" + postData.toJSONString());
        JSONObject respond = ImRequsetUtil.request(requestUrl, userSig, postData.toJSONString());
        logger.info(respond.toJSONString());
        if (respond != null) {
            String actionStatus = (String) respond.get("ActionStatus");
            if ("OK".equalsIgnoreCase(actionStatus)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 修改好友备注
     *
     * @param userId
     * @param friendUserId
     * @param remark
     * @return
     */
    @Override
    public boolean updateFirendRemark(String userId, String friendUserId, String remark) {
        JSONObject postData = new JSONObject();
        postData.put("From_Account", userId);
        JSONObject updateItem = new JSONObject();
        updateItem.put("To_Account", friendUserId);
        JSONObject snsItem = new JSONObject();
        snsItem.put("Tag", "Tag_SNS_IM_Remark");
        snsItem.put("Value", remark);
        JSONArray snsItemArray = new JSONArray();
        snsItemArray.add(snsItem);
        updateItem.put("SnsItem", snsItemArray);
        JSONArray updateItemArray = new JSONArray();
        updateItemArray.add(updateItem);
        postData.put("UpdateItem", updateItemArray);
        return imRequest(postData, "v4/sns/friend_update");
    }

    /**
     * 删除好友
     *
     * @param userId
     * @param friendUserId
     * @return
     */
    @Override
    public boolean deleteFirend(String userId, String friendUserId) {
        JSONObject postData = new JSONObject();
        postData.put("From_Account", userId);
        JSONArray deleteItemArray = new JSONArray();
        deleteItemArray.add(friendUserId);
        postData.put("To_Account", deleteItemArray);
        postData.put("DeleteType", "Delete_Type_Both");
        return imRequest(postData, "v4/sns/friend_delete");
    }

    /**
     * 删除所有好友
     *
     * @param userId
     * @return
     */
    @Override
    public boolean deleteAllFirend(String userId) {
        JSONObject postData = new JSONObject();
        postData.put("From_Account", userId);
        return imRequest(postData, "v4/sns/friend_delete_all");
    }

    /**
     * 校验好友
     *
     * @param userId
     * @param friendUserId
     * @return
     */
    @Override
    public boolean checkFirend(String userId, String friendUserId) {
        JSONObject postData = new JSONObject();
        postData.put("From_Account", userId);
        JSONArray checkUserArray = new JSONArray();
        checkUserArray.add(friendUserId);
        postData.put("To_Account", checkUserArray);
        postData.put("CheckType", "CheckResult_Type_Both");
        return imRequest(postData, "v4/sns/friend_check");
    }

    /**
     * 分页查询好友列表
     *
     * @param userId
     * @param startIndex
     * @return
     */
    @Override
    public FrindPageBean queryFriendByPage(String userId, Integer startIndex) {
        FrindPageBean frindPageBean = null;
        JSONObject postData = new JSONObject();
        postData.put("From_Account", userId);
        postData.put("StartIndex", startIndex);
        String userSig = imAccountService.genUserSig(ImSetting.IDENTIFIER);
        logger.info("request:" + postData.toJSONString());
        JSONObject respond = ImRequsetUtil.request("v4/sns/friend_get", userSig, postData.toJSONString());
        logger.info(respond.toJSONString());
        if (respond != null) {
            String actionStatus = (String) respond.get("ActionStatus");
            if ("OK".equalsIgnoreCase(actionStatus)) {
                frindPageBean = new FrindPageBean();
                frindPageBean.setNextStartIndex(respond.getInteger("NextStartIndex"));
                frindPageBean.setFriendNum(respond.getInteger("FriendNum"));
                List<FriendInfo> friendData = new ArrayList<>();
                JSONArray userDataItem = respond.getJSONArray("UserDataItem");
                if (userDataItem != null && userDataItem.size() > 0) {
                    for (int i = 0; i < userDataItem.size(); i++) {
                        FriendInfo friendInfo = new FriendInfo();
                        JSONObject userData = userDataItem.getJSONObject(i);
                        friendInfo.setUserId(userData.getString("To_Account"));
                        JSONArray valueItem = userData.getJSONArray("ValueItem");
                        if (valueItem != null && valueItem.size() > 0) {
                            for (int j = 0; j < valueItem.size(); j++) {
                                JSONObject value = valueItem.getJSONObject(j);
                                if (value.getString("Tag").equals("Tag_SNS_IM_Remark")) {
                                    friendInfo.setRemark(value.getString("Value"));
                                }
                            }
                        }
                        friendData.add(friendInfo);
                    }
                }
                frindPageBean.setFriendData(friendData);

                /**
                 * TODO 问题三 在日志中打印所有好友的ID
                 */
                for (FriendInfo info : friendData) {
                    logger.info(info.getUserId());
                }


                /**
                 * END
                 */
            }
        }
        return frindPageBean;
    }
}



